using Microsoft.AspNetCore.Mvc;
using WebRtcProject.Services;

namespace WebRtcProject.Controllers
{
    /// <summary>
    /// Consul 服务发现和配置管理控制器
    /// 提供服务注册、发现、健康检查和配置管理的API接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class ConsulController : ControllerBase
    {
        private readonly ConsulService _consulService;
        private readonly ILogger<ConsulController> _logger;

        public ConsulController(ConsulService consulService, ILogger<ConsulController> logger)
        {
            _consulService = consulService;
            _logger = logger;
        }

        /// <summary>
        /// 获取Consul服务状态
        /// </summary>
        [HttpGet("status")]
        public async Task<IActionResult> GetStatus()
        {
            try
            {
                var status = await _consulService.GetServiceStatusAsync();
                return Ok(status);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取Consul服务状态失败");
                return StatusCode(500, new { error = "获取服务状态失败", message = ex.Message });
            }
        }

        /// <summary>
        /// 检查Consul连接健康状态
        /// </summary>
        [HttpGet("health")]
        public async Task<IActionResult> CheckHealth()
        {
            try
            {
                var isHealthy = await _consulService.IsHealthyAsync();
                return Ok(new { 
                    healthy = isHealthy, 
                    message = isHealthy ? "Consul连接正常" : "Consul连接失败",
                    timestamp = DateTime.UtcNow
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "检查Consul健康状态失败");
                return StatusCode(500, new { 
                    healthy = false, 
                    error = "健康检查失败", 
                    message = ex.Message 
                });
            }
        }

        /// <summary>
        /// 手动注册服务
        /// </summary>
        [HttpPost("register")]
        public async Task<IActionResult> RegisterService()
        {
            try
            {
                await _consulService.RegisterServiceAsync();
                return Ok(new { message = "服务注册成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "手动注册服务失败");
                return StatusCode(500, new { error = "服务注册失败", message = ex.Message });
            }
        }

        /// <summary>
        /// 手动注销服务
        /// </summary>
        [HttpPost("deregister")]
        public async Task<IActionResult> DeregisterService()
        {
            try
            {
                await _consulService.DeregisterServiceAsync();
                return Ok(new { message = "服务注销成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "手动注销服务失败");
                return StatusCode(500, new { error = "服务注销失败", message = ex.Message });
            }
        }

        /// <summary>
        /// 发现指定服务的所有实例
        /// </summary>
        [HttpGet("services/{serviceName}")]
        public async Task<IActionResult> DiscoverService(string serviceName)
        {
            try
            {
                var services = await _consulService.DiscoverServicesAsync(serviceName);
                return Ok(new { 
                    serviceName = serviceName,
                    instanceCount = services.Count,
                    instances = services
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "服务发现失败 - 服务: {ServiceName}", serviceName);
                return StatusCode(500, new { error = "服务发现失败", message = ex.Message });
            }
        }

        /// <summary>
        /// 获取所有已注册的服务列表
        /// </summary>
        [HttpGet("services")]
        public async Task<IActionResult> GetAllServices()
        {
            try
            {
                var services = await _consulService.GetAllServicesAsync();
                return Ok(new { 
                    totalServices = services.Count,
                    services = services
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取服务列表失败");
                return StatusCode(500, new { error = "获取服务列表失败", message = ex.Message });
            }
        }

        /// <summary>
        /// 获取配置值
        /// </summary>
        [HttpGet("config/{key}")]
        public async Task<IActionResult> GetConfig(string key)
        {
            try
            {
                var value = await _consulService.GetConfigValueAsync(key);
                if (value != null)
                {
                    return Ok(new { key = key, value = value });
                }
                else
                {
                    return NotFound(new { message = $"配置键 '{key}' 不存在" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取配置失败 - 键: {Key}", key);
                return StatusCode(500, new { error = "获取配置失败", message = ex.Message });
            }
        }

        /// <summary>
        /// 设置配置值
        /// </summary>
        [HttpPost("config")]
        public async Task<IActionResult> SetConfig([FromBody] SetConfigRequest request)
        {
            try
            {
                if (string.IsNullOrEmpty(request.Key))
                {
                    return BadRequest(new { error = "配置键不能为空" });
                }

                var success = await _consulService.SetConfigValueAsync(request.Key, request.Value ?? "");
                
                if (success)
                {
                    return Ok(new { message = "配置设置成功", key = request.Key });
                }
                else
                {
                    return StatusCode(500, new { error = "配置设置失败" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "设置配置失败 - 键: {Key}", request.Key);
                return StatusCode(500, new { error = "设置配置失败", message = ex.Message });
            }
        }

        /// <summary>
        /// 批量获取配置
        /// </summary>
        [HttpPost("config/batch-get")]
        public async Task<IActionResult> BatchGetConfigs([FromBody] BatchGetConfigRequest request)
        {
            try
            {
                var results = new Dictionary<string, string?>();
                
                foreach (var key in request.Keys)
                {
                    var value = await _consulService.GetConfigValueAsync(key);
                    results[key] = value;
                }

                return Ok(new { 
                    requestedKeys = request.Keys,
                    configs = results
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量获取配置失败");
                return StatusCode(500, new { error = "批量获取配置失败", message = ex.Message });
            }
        }

        /// <summary>
        /// 批量设置配置
        /// </summary>
        [HttpPost("config/batch-set")]
        public async Task<IActionResult> BatchSetConfigs([FromBody] BatchSetConfigRequest request)
        {
            try
            {
                var results = new Dictionary<string, bool>();
                
                foreach (var config in request.Configs)
                {
                    var success = await _consulService.SetConfigValueAsync(config.Key, config.Value);
                    results[config.Key] = success;
                }

                var successCount = results.Values.Count(success => success);
                
                return Ok(new { 
                    totalConfigs = request.Configs.Count,
                    successCount = successCount,
                    failedCount = request.Configs.Count - successCount,
                    results = results
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量设置配置失败");
                return StatusCode(500, new { error = "批量设置配置失败", message = ex.Message });
            }
        }
    }

    /// <summary>
    /// 设置配置请求模型
    /// </summary>
    public class SetConfigRequest
    {
        public string Key { get; set; } = string.Empty;
        public string? Value { get; set; }
    }

    /// <summary>
    /// 批量获取配置请求模型
    /// </summary>
    public class BatchGetConfigRequest
    {
        public List<string> Keys { get; set; } = new();
    }

    /// <summary>
    /// 批量设置配置请求模型
    /// </summary>
    public class BatchSetConfigRequest
    {
        public List<ConfigItem> Configs { get; set; } = new();
    }

    /// <summary>
    /// 配置项模型
    /// </summary>
    public class ConfigItem
    {
        public string Key { get; set; } = string.Empty;
        public string Value { get; set; } = string.Empty;
    }
} 